package com.stone.framework.batch.tasklet;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.util.Assert;

/**
 * 存储过程tasklet
 * 
 * @author ybliu
 * @date 2020/07/27
 */
public class StoredProcedureTasklet implements Tasklet, InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(StoredProcedureTasklet.class);

    private String packageName;
    private String procedureName;
    private Object[] paramArray = new Object[0];
    private DataSource dataSource;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        LOGGER.info("执行存储过程: {}.{}", this.packageName, this.procedureName);
        SimpleJdbcCall call =
            new SimpleJdbcCall(this.dataSource).withProcedureName(this.procedureName).withCatalogName(this.packageName);
        call.execute(paramArray);
        contribution.setExitStatus(ExitStatus.COMPLETED);
        return RepeatStatus.FINISHED;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.dataSource, "dataSource must not be null");
        Assert.notNull(this.procedureName, "procedureName must not be null");
    }

    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }

    public void setProcedureName(String procedureName) {
        this.procedureName = procedureName;
    }

    public void setParamArray(Object... paramArray) {
        this.paramArray = paramArray;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

}
